<template>
  <div class="content">
    <el-card class="box-card" shadow="always" style="width: 80%">
      <h3 align="center">新增标案</h3>
      <el-descriptions title="标案信息" class="margin-top" :column="3" border>
        <el-descriptions-item label="标案名称">
          <el-input v-model="form.tenderInfoPostParams.tenderName" />
        </el-descriptions-item>
        <el-descriptions-item label="标案编码" :span="2">
          <el-input
            placeholder="NJTECH-SCIENCETECHONOLOGY-20211217-001 按此格式填写"
            v-model="form.tenderInfoPostParams.tenderCode"
          />
        </el-descriptions-item>
        <el-descriptions-item label="招标类型">
          <el-select v-model="form.tenderInfoPostParams.tenderType" disabled>
            <el-option
              v-for="item in productTypes"
              :key="item.id"
              :label="item.productType"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item label="招标项目">
          <el-select
            v-model="form.tenderInfoPostParams.tenderProject"
            clearable
            filterable
            @change="projectSelect"
            placeholder="请选择招标项目"
          >
            <el-option
              v-for="item in projects"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item label="立标日期">
          <el-date-picker
            v-model="form.tenderInfoPostParams.tenderTime"
            type="datetime"
            placeholder="选择立标日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00"
          >
          </el-date-picker>
        </el-descriptions-item>
        <el-descriptions-item label="招标负责人">
          <el-input v-model="form.tenderInfoPostParams.tenderCharge" />
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          <el-input v-model="form.tenderInfoPostParams.tenderPhone" />
        </el-descriptions-item>
        <el-descriptions-item label="固定电话">
          <el-input v-model="form.tenderInfoPostParams.tenderTel" />
        </el-descriptions-item>
        <el-descriptions-item label="招标方式">
          <el-select
            v-model="form.tenderInfoPostParams.tenderMode"
            clearable
            placeholder="请选择招标方式"
          >
            <el-option label="公开招标" value="0"> </el-option>
            <el-option label="非公开招标" value="1"> </el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item label="竞价方式">
          <el-select
            v-model="form.tenderInfoPostParams.biddingMode"
            clearable
            placeholder="请选择竞价模式"
            @change="selectedChange"
          >
            <el-option label="一轮竞价" value="1"> </el-option>
            <el-option label="二轮竞价" value="2"> </el-option>
            <el-option label="三轮竞价" value="3"> </el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item
          label="显示选择"
          :span="2"
          style="text-align: center"
        >
          <div class="exhibition-div">
            <el-switch
              v-model="form.tenderInfoPostParams.tenderRanking"
              active-color="#13ce66"
              inactive-text="竞价排名"
              style="margin-right: 30px"
            >
            </el-switch>

            <el-switch
              v-model="form.tenderInfoPostParams.minimumPrice"
              active-color="#13ce66"
              inactive-text="最低价格"
              style="margin-left: 30px"
            >
            </el-switch>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="招标说明">
          <el-input
            type="textarea"
            placeholder="请输入标案说明内容"
            v-model="form.tenderInfoPostParams.tenderExplain"
          />
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="招标产品" class="margin-top" border>
        <el-descriptions-item label="产品选择">
          <el-select
            v-model="productSelectId"
            multiple
            placeholder="请选择招标产品"
            :disabled="isDisabled"
            style="width: 100%"
            @change="productSelect"
          >
            <el-option
              v-for="item in products"
              :key="item.id"
              :label="item.productName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        class="margin-top"
        :column="2"
        border
        v-for="item in productss"
        :key="item.id"
      >
        <el-descriptions-item label="产品名称">
          <el-input v-model="item.productName" disabled />
        </el-descriptions-item>

        <el-descriptions-item label="采购数量">
          <!-- <el-input-number v-model="item.purchaseData" controls-position="right" :min="0" :max="999" @change="handleChange"/> -->
          <el-input-number
            v-model="item.purchaseData"
            controls-position="right"
            :min="0"
            :max="999"
          ></el-input-number>
        </el-descriptions-item>
        <el-descriptions-item label="规格型号">
          <el-input v-model="item.productModel" disabled />
        </el-descriptions-item>
        <el-descriptions-item label="采购单位">
          <el-input v-model="item.productUnit" disabled />
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="竞价时间" class="margin-top" :column="2" border>
        <el-descriptions-item
          v-for="(time, index) in times"
          :key="index"
          :span="2"
        >
          <template slot="label">
            {{ index + 1 + "轮竞价" }}
          </template>
          <el-date-picker
            type="datetimerange"
            v-model="time.timeArr"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="center"
          >
          </el-date-picker>
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="定价时间" class="margin-top" :column="1" border>
        <el-descriptions-item label="定价时间">
          <el-date-picker
            v-model="calibration"
            type="datetimerange"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="center"
          >
          </el-date-picker>
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="邀约供应商" class="margin-top" :column="3" border>
        <el-descriptions-item label="发出邀约" :span:="3">
          <el-select
            v-model="form.supplierIds"
            style="width: 100%"
            value-key=""
            :disabled="isSupplierDisabled"
            placeholder="请选择供应商"
            clearable
            filterable
            multiple
            @change="SelectSupplier"
          >
            <el-option
              v-for="item in suppliers"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions
        class="margin-top"
        :column="2"
        border
        v-for="(item, index) in supplier"
        :key="index"
      >
        <el-descriptions-item label="供应商名">
          <el-input v-model="item.username" disabled />
        </el-descriptions-item>

        <el-descriptions-item label="公司名称">
          <el-input v-model="item.companyName" disabled />
        </el-descriptions-item>
        <el-descriptions-item label="联系方式">
          <el-input v-model="item.mobilePhone" disabled />
        </el-descriptions-item>
        <el-descriptions-item label="积分数量">
          <el-input v-model="item.integral" disabled />
        </el-descriptions-item>
      </el-descriptions>

      <div class="footer">
        <el-button @click="cancel" style="margin-right: 20px">取 消</el-button>
        <el-button type="primary" @click="ok" style="margin-left: 20px"
          >确 定</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
class TimeItem {
  constructor() {
    this.timeArr = [];
  }
}
import { mapGetters } from "vuex";
import {
  getTypeWithProjectAndProducts,
  getProductsByProjId,
  getAllSupplierByTenderProduct,
  addTenderInfo,
} from "@/api/purchaser-tender.js";

export default {
  props: {},
  data() {
    return {
      times: [new TimeItem()],
      calibration: [],
      productss: [],
      supplier: [],
      form: {
        supplierIds: [],
        tenderInfoPostParams: {
          biddingMode: "1",
          calibrationEnd: "",
          calibrationStart: "",
          minimumPrice: true,
          purchaserId: "",
          roleId: "",
          tenderCharge: "",
          tenderCode: "",
          tenderExplain: "",
          tenderMode: "0",
          tenderName: "",
          tenderPhone: "",
          tenderProducts: [],
          tenderProject: "",
          tenderRanking: true,
          tenderTel: "",
          tenderTime: "",
          tenderType: "招标项目带出",
          timeNodes: [],
        },
      },
      projects: [], // 获取所有的项目
      products: [], // 获取所有的产品
      isDisabled: true, // 选择产品禁选
      productSelectId: [], // 用户选中的产品
      isSupplierDisabled: true,
      suppliers: [],
      pickerOptions: {
        disabledDate: (time) => {
          const start = new Date().getTime() + 3600 * 1000 * 24 * 3;
          const end = start + 3600 * 1000 * 24 * 30;
          return time.getTime() < start || time.getTime() > end;
        },
      },
    };
  },
  computed: {
    ...mapGetters(["accountId", "roles"]),
    productTypes() {
      // 先获取到所有的类型
      let arr = this.projects.map((info) => {
        return info.typeBriefInfo;
      });
      let obj = {};
      return arr.reduce((item, next) => {
        obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
        return item;
      }, []);
    },
  },
  created() {
    this.getProjects();
  },
  methods: {
    // 动态获取日期组件个数
    selectedChange(val) {
      if (!val) {
        this.form.tenderInfoPostParams.biddingMode = "1";
        val = "1";
      }
      this.times.splice(0, this.times.length);
      for (let i = 0; i < parseInt(val); i++) {
        this.times.push(new TimeItem());
      }
    },
    async getProjects() {
      const res = await getTypeWithProjectAndProducts({
        purchaserId: this.$store.getters.accountId,
      });
      if (res.code === 200) this.projects = res.data;
      this.form.tenderInfoPostParams.tenderCharge = this.$store.getters.name;
      this.form.tenderInfoPostParams.tenderPhone =
        this.$store.getters.mobilePhone;
      console.log(this.form.tenderInfoPostParams.tenderPhone);
    },
    projectSelect(val) {
      if (val) {
        // 先清空掉数据
        this.productss = []; // 创建产品dom
        this.productSelectId = [];
        const res = this.projects.filter((info) => {
          return info.id === val;
        });
        this.form.tenderInfoPostParams.tenderType = res[0].typeBriefInfo.id;
        // 调用函数
        this.getProducts(val);
      } else {
        this.form.tenderInfoPostParams.tenderType = "找遍项目带出";
        this.productss = []; // 创建产品dom
        this.productSelectId = [];
        this.isDisabled = true;
      }
    },

    productSelect(val) {
      this.suppliers.splice(0, this.suppliers.length);
      if (val.length !== 0) {
        this.getSupliers(val);
        // 清空数组
        this.productss.splice(0, this.productss.length);
        for (let i = 0; i < val.length; i++) {
          // val : productId数组
          // 产品数组过滤出对应产品对象
          let newProductItem = this.products.filter((item) => {
            return item.id == val[i];
          });
          newProductItem[0].purchaseData = 0;
          this.productss.push(newProductItem[0]);
        }
      } else {
        this.productss.splice(0, this.productss.length);
        this.suppliers = [];
        this.isSupplierDisabled = true;
      }
    },

    async getProducts(projectId) {
      const res = await getProductsByProjId({
        projectId: projectId,
        purchaserId: this.$store.getters.accountId,
      });
      if (res.code === 200) {
        this.products = res.data;
        this.isDisabled = false;
      }
    },

    async getSupliers(products) {
      const data = {
        pageParams: {
          page: 0,
          pageSize: 0,
        },
        productIds: products,
      };
      const res = await getAllSupplierByTenderProduct(data);
      if (res.code === 200) {
        this.suppliers = res.data.supplierByTenderProducts;
        this.isSupplierDisabled = false;
      }
    },

    SelectSupplier(val) {
      this.supplier.splice(0, this.supplier.length);
      for (let i = 0; i < val.length; i++) {
        let newSupplierItem = this.suppliers.filter((item) => {
          return item.id == val[i];
        });
        this.supplier.push(newSupplierItem[0]);
      }
    },

    initForm() {
      this.form = {
        supplierIds: [],
        tenderInfoPostParams: {
          biddingMode: 3,
          calibrationEnd: "",
          calibrationStart: "",
          minimumPrice: true,
          purchaserId: "",
          roleId: "",
          tenderCharge: "",
          tenderCode: "",
          tenderExplain: "",
          tenderMode: 0,
          tenderName: "",
          tenderPhone: "",
          tenderProducts: [],
          tenderProject: "",
          tenderRanking: true,
          tenderTel: "",
          tenderTime: "",
          tenderType: "",
          timeNodes: [],
        },
      };
    },
    cancel() {
      this.initForm();
      this.$router.go(-1);
    },
    ok() {
      this.form.tenderInfoPostParams.calibrationStart = this.calibration[0];
      this.form.tenderInfoPostParams.calibrationEnd = this.calibration[1];
      this.form.tenderInfoPostParams.purchaserId = this.accountId;
      this.form.tenderInfoPostParams.roleId = this.roles.toString();
      this.form.tenderInfoPostParams.timeNodes = this.times.map(
        (item, index) => {
          return {
            bindingStart: item.timeArr[0],
            bindingEnd: item.timeArr[1],
            round: index + 1,
          };
        }
      );
      this.form.tenderInfoPostParams.tenderProducts = this.productss.map(
        (item) => {
          return {
            productId: item.id,
            purchaseData: item.purchaseData,
            purchaseUnit: item.productUnit,
          };
        }
      );
      // console.log(this.form.tenderInfoPostParams.tenderProducts)
      // console.log(this.form.tenderInfoPostParams.timeNodes)
      // console.log(this.form);
      // this.$router.go(-1);
      addTenderInfo(this.form)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("标案新增成功");
            this.initForm();
            this.$router.go(-1);
          }
        })
        .catch((err) => {
          this.$message.success("失败,Cause:" + err);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.margin-top {
  margin-top: 20px;
}
.content {
  display: flex;
  justify-content: center;
  align-items: center;
}
.footer {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 15px;
}
.exhibition-div {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 15px;
}
</style>
